<template>
  <div class="app-container">
    <!-- 标签页切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="用户标签管理" name="userTags">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
          <el-form-item label="标签名称" prop="tagName">
            <el-input
              v-model="queryParams.tagName"
              placeholder="请输入标签名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="标签状态" clearable style="width: 200px">
              <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['homepage:usertags:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['homepage:usertags:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['homepage:usertags:remove']"
            >删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 调试信息 -->
        <el-alert v-if="tagList.length === 0 && !loading"
                  title="暂无数据"
                  type="info"
                  :description="`当前查询条件下没有找到用户标签数据。总数: ${total}`"
                  show-icon
                  style="margin-bottom: 20px;">
        </el-alert>

        <el-table v-loading="loading" :data="tagList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="标签ID" align="center" prop="id" />
          <el-table-column label="标签名称" align="center" prop="tagName" />
          <el-table-column label="标签描述" align="center" prop="description" />
          <el-table-column label="标签颜色" align="center" prop="color">
            <template #default="scope">
              <el-tag :color="scope.row.color" style="color: white;">{{ scope.row.tagName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                type="text"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['homepage:usertags:edit']"
              >修改</el-button>
              <el-button
                type="text"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['homepage:usertags:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>

      <!-- TB_TAG 标签管理 -->
      <el-tab-pane label="TB_TAG标签管理" name="tbTag">
        <el-form :model="tbTagQueryParams" ref="tbTagQueryRef" :inline="true" v-show="showSearch">
          <el-form-item label="标签名称" prop="tagName">
            <el-input
              v-model="tbTagQueryParams.tagName"
              placeholder="请输入标签名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleTbTagQuery"
            />
          </el-form-item>
          <el-form-item label="标签类型" prop="tagType">
            <el-select v-model="tbTagQueryParams.tagType" placeholder="标签类型" clearable style="width: 200px">
              <el-option label="兴趣爱好" value="1" />
              <el-option label="技能特长" value="2" />
              <el-option label="其他" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="tagStatus">
            <el-select v-model="tbTagQueryParams.tagStatus" placeholder="标签状态" clearable style="width: 200px">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleTbTagQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetTbTagQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleTbTagAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="tbTagSingle"
              @click="handleTbTagUpdate"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="tbTagMultiple"
              @click="handleTbTagDelete"
            >删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getTbTagList"></right-toolbar>
        </el-row>

        <!-- TB_TAG调试信息 -->
        <el-alert v-if="tbTagList.length === 0 && !tbTagLoading"
                  title="暂无TB_TAG数据"
                  type="info"
                  :description="`当前查询条件下没有找到TB_TAG标签数据。总数: ${tbTagTotal}`"
                  show-icon
                  style="margin-bottom: 20px;">
        </el-alert>

        <el-table v-loading="tbTagLoading" :data="tbTagList" @selection-change="handleTbTagSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="标签ID" align="center" prop="tagId" />
          <el-table-column label="标签名称" align="center" prop="tagName" />
          <el-table-column label="标签类型" align="center" prop="tagType">
            <template #default="scope">
              <el-tag v-if="scope.row.tagType === 1" type="primary">兴趣爱好</el-tag>
              <el-tag v-else-if="scope.row.tagType === 2" type="success">技能特长</el-tag>
              <el-tag v-else-if="scope.row.tagType === 3" type="info">其他</el-tag>
              <el-tag v-else type="warning">{{ scope.row.tagType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="标签状态" align="center" prop="tagStatus">
            <template #default="scope">
              <el-tag :type="scope.row.tagStatus === 1 ? 'success' : 'danger'">
                {{ scope.row.tagStatus === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                type="text"
                icon="Edit"
                @click="handleTbTagUpdate(scope.row)"
              >修改</el-button>
              <el-button
                type="text"
                icon="Delete"
                @click="handleTbTagDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="tbTagTotal>0"
          :total="tbTagTotal"
          v-model:page="tbTagQueryParams.pageNum"
          v-model:limit="tbTagQueryParams.pageSize"
          @pagination="getTbTagList"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- 添加或修改用户标签对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="tagRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入标签描述" />
        </el-form-item>
        <el-form-item label="标签颜色" prop="color">
          <el-color-picker v-model="form.color" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改TB_TAG标签对话框 -->
    <el-dialog :title="tbTagTitle" v-model="tbTagOpen" width="500px" append-to-body>
      <el-form ref="tbTagRef" :model="tbTagForm" :rules="tbTagRules" label-width="80px">
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="tbTagForm.tagName" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签类型" prop="tagType">
          <el-select v-model="tbTagForm.tagType" placeholder="请选择标签类型" style="width: 100%">
            <el-option label="兴趣爱好" :value="1" />
            <el-option label="技能特长" :value="2" />
            <el-option label="其他" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签状态" prop="tagStatus">
          <el-radio-group v-model="tbTagForm.tagStatus">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTbTagForm">确 定</el-button>
          <el-button @click="cancelTbTag">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserTags">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { listUserTags, getUserTags, delUserTags, addUserTags, updateUserTags } from "@/api/homepage/user-tags";
import { listTbTag, getTbTag, delTbTag, addTbTag, updateTbTag } from "@/api/homepage/tb-tag";

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

// 用户标签相关变量
const tagList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// TB_TAG相关变量
const activeTab = ref("tbTag");
const tbTagList = ref([]);
const tbTagOpen = ref(false);
const tbTagLoading = ref(true);
const tbTagIds = ref([]);
const tbTagSingle = ref(true);
const tbTagMultiple = ref(true);
const tbTagTotal = ref(0);
const tbTagTitle = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tagName: undefined,
    status: undefined
  },
  rules: {
    tagName: [
      { required: true, message: "标签名称不能为空", trigger: "blur" }
    ],
    color: [
      { required: true, message: "标签颜色不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "排序不能为空", trigger: "blur" }
    ]
  }
});

const tbTagData = reactive({
  tbTagForm: {},
  tbTagQueryParams: {
    pageNum: 1,
    pageSize: 10,
    tagName: undefined,
    tagType: undefined,
    tagStatus: undefined
  },
  tbTagRules: {
    tagName: [
      { required: true, message: "标签名称不能为空", trigger: "blur" }
    ],
    tagType: [
      { required: true, message: "标签类型不能为空", trigger: "change" }
    ],
    tagStatus: [
      { required: true, message: "标签状态不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);
const { tbTagQueryParams, tbTagForm, tbTagRules } = toRefs(tbTagData);

/** 查询用户标签列表 */
function getList() {
  loading.value = true;
  listUserTags(queryParams.value).then(response => {
    tagList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(error => {
    console.error('获取用户标签列表失败:', error);
    proxy.$modal.msgError('获取用户标签列表失败: ' + (error.message || '网络错误'));
    tagList.value = [];
    total.value = 0;
    loading.value = false;
  });
}

/** 查询TB_TAG标签列表 */
function getTbTagList() {
  tbTagLoading.value = true;
  listTbTag(tbTagQueryParams.value).then(response => {
    tbTagList.value = response.rows || [];
    tbTagTotal.value = response.total || 0;
    tbTagLoading.value = false;
  }).catch(error => {
    console.error('获取TB_TAG标签列表失败:', error);
    proxy.$modal.msgError('获取TB_TAG标签列表失败: ' + (error.message || '网络错误'));
    tbTagList.value = [];
    tbTagTotal.value = 0;
    tbTagLoading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    tagName: undefined,
    description: undefined,
    color: "#409EFF",
    sort: 0,
    status: "0"
  };
  proxy.resetForm("tagRef");
}

// TB_TAG取消按钮
function cancelTbTag() {
  tbTagOpen.value = false;
  resetTbTag();
}

// TB_TAG表单重置
function resetTbTag() {
  tbTagForm.value = {
    tagId: undefined,
    tagName: undefined,
    tagType: undefined,
    tagStatus: 1
  };
  proxy.resetForm("tbTagRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** TB_TAG搜索按钮操作 */
function handleTbTagQuery() {
  tbTagQueryParams.value.pageNum = 1;
  getTbTagList();
}

/** TB_TAG重置按钮操作 */
function resetTbTagQuery() {
  proxy.resetForm("tbTagQueryRef");
  handleTbTagQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// TB_TAG多选框选中数据
function handleTbTagSelectionChange(selection) {
  tbTagIds.value = selection.map(item => item.tagId);
  tbTagSingle.value = selection.length != 1;
  tbTagMultiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户标签";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getUserTags(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户标签";
  });
}

/** TB_TAG新增按钮操作 */
function handleTbTagAdd() {
  resetTbTag();
  tbTagOpen.value = true;
  tbTagTitle.value = "添加TB_TAG标签";
}

/** TB_TAG修改按钮操作 */
function handleTbTagUpdate(row) {
  resetTbTag();
  const tagId = row.tagId || tbTagIds.value;
  getTbTag(tagId).then(response => {
    tbTagForm.value = response.data;
    tbTagOpen.value = true;
    tbTagTitle.value = "修改TB_TAG标签";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["tagRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateUserTags(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUserTags(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** TB_TAG提交按钮 */
function submitTbTagForm() {
  proxy.$refs["tbTagRef"].validate(valid => {
    if (valid) {
      if (tbTagForm.value.tagId != null) {
        updateTbTag(tbTagForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          tbTagOpen.value = false;
          getTbTagList();
        });
      } else {
        addTbTag(tbTagForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          tbTagOpen.value = false;
          getTbTagList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除用户标签编号为"' + ids + '"的数据项？').then(function() {
    return delUserTags(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** TB_TAG删除按钮操作 */
function handleTbTagDelete(row) {
  const tagIds = row.tagId || tbTagIds.value;
  proxy.$modal.confirm('是否确认删除TB_TAG标签编号为"' + tagIds + '"的数据项？').then(function() {
    return delTbTag(tagIds);
  }).then(() => {
    getTbTagList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 标签页切换 */
function handleTabClick(tab) {
  if (tab.name === 'userTags') {
    getList();
  } else if (tab.name === 'tbTag') {
    getTbTagList();
  }
}

getTbTagList();
</script> 